package com.lagou.code.service.impl;

import com.lagou.code.client.EmailFeignClient;
import com.lagou.code.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author jacken
 * @date 2020/4/25 7:09 PM
 */
@Service
public class CodeServiceImpl implements CodeService {

  @Autowired
  private StringRedisTemplate stringRedisTemplate;

  @Autowired
  private EmailFeignClient emailFeignClient;

  @Override
  public Boolean create(String email) {
    // 生成验证码
    Random random = new Random();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 6 ; i++) {
      sb.append(random.nextInt(10));
    }

    if (!StringUtils.isEmpty(stringRedisTemplate.opsForValue().get(email))) {
      return true;
    }

    stringRedisTemplate.opsForValue().set(email, sb.toString(), 10, TimeUnit.MINUTES);
    // 发送验证码
    return emailFeignClient.sendCode(email, sb.toString());
  }

  @Override
  public Integer validate(String email, String code) {
    String value = stringRedisTemplate.opsForValue().get(email);
    if (StringUtils.isEmpty(value)) {
      return 1;
    }

    return value.equals(code) ? 0 : 1;
  }
}
